package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


/**
 * @author 14280
 * 上传文件
 * username,age,file
 */
@Slf4j
@RestController
public class UploadController {
    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;
    //private static final String UPLOAD_DIR = "D:/img/UUID";
    @PostMapping("/upload")
    public Result upload(@RequestParam(value = "file") MultipartFile file) {
        log.info("文件上传{}", file);
        try {
            //文件的url
            String url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
            return Result.success(url);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return Result.error("上传文件失败");
        }

    }
   /* @PostMapping("/upload")
    public Result upload(@RequestParam String username, @RequestParam Integer age, @RequestParam(value = "file") MultipartFile file) throws Exception {
        log.info("上传文件：{},{},{}", username, age, file);
        //判断是否为空，空的话直接报error信息
        if (!file.isEmpty()) {
            //获取 源文件名，包括扩展名
            String filename = file.getOriginalFilename();
            //获取 uuid
            String uuid = UUID.randomUUID().toString();
            //filename.substring(filename.lastIndexOf(".")+1);截取出来的是png
            //截取后缀
            String substring = filename.substring(filename.lastIndexOf("."));
            //新文件名生成
            String newFilename = uuid + substring;
            //在内存中创建该路径的目录对象
            File dir = new File(UPLOAD_DIR);
            //判断目录是否真的存在，不存在就创建
            if (!dir.exists()) {
                dir.mkdirs();
            }
            try {
                file.transferTo(new File(UPLOAD_DIR, newFilename));
            } catch (IOException e) {
                //上传失败
                log.error("文件上传失败", e);
                Result.error("文件上传失败");
            }
            return Result.success();
        }
        return Result.error("文件不能为空");
    }*/
}
